package pers.cj.pdos.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.BusinessSet;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.excel.ExcelGoodsTransfer;
import pers.cj.pdos.excel.ExcelPayWait;
import pers.cj.pdos.excel.ExcelPayWaitDetail;
import pers.cj.pdos.service.IPayWaitService;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.PayWaitVo;
import pers.cj.pdos.vo.UserVo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2020-01-19
 */
@Controller
@RequestMapping("/funds")
public class PayWaitController extends BaseController {
    @Autowired
    IPayWaitService payWaitService;

    @RequiresPermissions("payOrder:query")
    @RequestMapping("/payWait")
    public String payWait() {
        return "funds/payWait";
    }

    @RequiresPermissions("payOrder:query")
    @RequestMapping("/payWaitDetail")
    public String payWaitDetail(Model model,String providerId) {
        model.addAttribute("providerId",providerId);
        return "funds/payWaitDetail";
    }

    @ResponseBody
    @RequiresPermissions("payOrder:query")
    @RequestMapping("/payWait/getDetailList")
    public ResponseList getDetailList(String providerId,
                                      int page,
                                      int limit,
                                      String close,
                                      String search,
                                      String no,
                                      String remark,
                                      String userId,
                                      String date1,
                                      String date2,
                                      String flag,
                                      String storeId)
    {
        if (Utils.isEmpty(providerId)){
            return ResponseList.fail("providerId不能为空");
        }
        UserVo userVo = getLoginUserVo();
        List<Map> list = payWaitService.listDetail(providerId,
                page,
                limit,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(remark),
                userId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genInteger(flag),
                PdosUtils.getViewOtherStoreId(userVo,storeId));
        long count = payWaitService.countDetail(providerId,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(remark),
                userId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genInteger(flag),
                PdosUtils.getViewOtherStoreId(userVo,storeId));
        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequiresPermissions("payOrder:query")
    @RequestMapping("/payWait/getList")
    public ResponseList getList(int page,
                                int limit,
                                String providerTypeId,
                                String notNeedPay,
                                String providerNoStop,
                                String search)
    {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<Map> list = payWaitService.listVo(company.getId(),
                page,
                limit,
                PdosUtils.getViewOtherStoreId(userVo,null),
                providerTypeId,
                Utils.genBoolean(notNeedPay),
                Utils.genBoolean(providerNoStop),
                Utils.genLikeData(search));
        long count = payWaitService.count(company.getId(),
                PdosUtils.getViewOtherStoreId(userVo,null),
                providerTypeId,
                Utils.genBoolean(notNeedPay),
                Utils.genBoolean(providerNoStop),
                Utils.genLikeData(search));
        return ResponseList.success(count,list);
    }


    @ResponseBody
    @RequiresPermissions("payOrder:query")
    @RequestMapping("/payWait/getVoByProvider")
    public ResponseData getVoByProvider(String providerId){
        PayWaitVo payWaitVo = payWaitService.getVoByProvider(providerId);
        if (payWaitVo == null) {
            return ResponseData.fail("未获取到信息");
        }
        return ResponseData.success(payWaitVo);
    }

    @ResponseBody
    @RequiresPermissions("payOrder:export")
    @RequestMapping("/payWait/export")
    public ResponseData export(String providerTypeId,
                               String notNeedPay,
                               String providerNoStop,
                               String search) {

        String fileName = "供应商应付欠款列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelPayWait.class);
            sheet1.setSheetName("供应商应付欠款信息");
            writer.write(genExcelList(providerTypeId,notNeedPay,providerNoStop,search), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }


    @ResponseBody
    @RequiresPermissions("payOrder:export")
    @RequestMapping("/payWait/exportDetail")
    public ResponseData exportDetail(String providerId,
                                     String close,
                                     String search,
                                     String no,
                                     String remark,
                                     String userId,
                                     String date1,
                                     String date2,
                                     String flag,
                                     String storeId) {

        UserVo userVo = getLoginUserVo();
        List<Map> list = payWaitService.listDetail(providerId,
                null,
                null,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(remark),
                userId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genInteger(flag),
                PdosUtils.getViewOtherStoreId(userVo,storeId));

        String fileName = "供应商应付欠款详细" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelPayWaitDetail.class);
            sheet1.setSheetName("供应商应付欠款详细信息");
            writer.write(genExcelDetailList(list), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    private List<ExcelPayWaitDetail> genExcelDetailList(List<Map> maplist) {

        BusinessSet businessSet = getBusinessSet();
        List<ExcelPayWaitDetail> list = new ArrayList<>();
        for (Map map : maplist) {
            ExcelPayWaitDetail excel = new ExcelPayWaitDetail();
            excel.setDate(PdosUtils.genDateFromMap(map,"date"));
            excel.setNo((String) map.get("no"));
            excel.setStore((String) map.get("store"));
            excel.setUser((String) map.get("user"));
            excel.setType((String) map.get("type"));
            excel.setSettAccount((String) map.get("settAccount"));

            excel.setPayWait(PdosUtils.getPrice((BigDecimal) map.get("payWait"),businessSet));
            excel.setPay(PdosUtils.getPrice((BigDecimal) map.get("pay"),businessSet));
            excel.setDiscount(PdosUtils.getPrice((BigDecimal) map.get("discount"),businessSet));
            excel.setShouldPay(PdosUtils.getPrice((BigDecimal) map.get("shouldPay"),businessSet));
            excel.setRemark((String) map.get("remark"));

            list.add(excel);
        }
        return list;
    }


    private List<ExcelPayWait> genExcelList(String providerTypeId,
                                            String notNeedPay,
                                            String providerNoStop,
                                            String search) {
        BusinessSet businessSet = getBusinessSet();
        UserVo userVo = getLoginUserVo();
        List<ExcelPayWait> list = new ArrayList<>();
        List<Map> mapList = payWaitService.listVo(getCompany().getId(),
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,null),
                providerTypeId,
                Utils.genBoolean(notNeedPay),
                Utils.genBoolean(providerNoStop),
                Utils.genLikeData(search));
        for (Map map : mapList) {
            ExcelPayWait excel = new ExcelPayWait();
            excel.setNo((String) map.get("no"));
            excel.setName((String) map.get("name"));
            excel.setContacts((String) map.get("contacts"));
            excel.setPhone((String) map.get("phone"));

            excel.setTotal(PdosUtils.getPrice((BigDecimal) map.get("total"),businessSet));
            excel.setHasPay(PdosUtils.getPrice((BigDecimal) map.get("hasPay"),businessSet));
            excel.setDiscount(PdosUtils.getPrice((BigDecimal) map.get("discount"),businessSet));
            excel.setWaitPay(PdosUtils.getPrice((BigDecimal) map.get("waitPay"),businessSet));

            list.add(excel);
        }
        return list;
    }

}
